import { defineStore } from "pinia";
import WebsocketClass from "@/utils/websocket";
import { useUserStore } from "./user";
export const useWebsocketStore = defineStore("websocket", {
  state: () => ({
    response: null,
    socket: null
  }),
  actions: {
    /**
     * 初始化websocket
     */
    init() {
      if (!this.socket) {
        const url = import.meta.env.VITE_WS_URL + useUserStore().userinfo.token;
        this.socket = new WebsocketClass(url, data => {
          this.response = data;
          if (data.data) {
            switch (data.data.type) {
              case -1:
                break;
              default:
                break;
            }
          }
        });
        this.socket.connect();
      }
    },

    /**
     * 发送信息
     * @param {*} data
     */
    send(data) {
      const params = {
        type: 1,
        requestBody: data
      };
      console.log("✈️:~~", params);
      this.socket.send(params);
    },

    /**
     * 手动断开websocket
     */
    close() {
      if (this.socket) {
        this.socket.close();
      }
      this.response = null;
      this.socket = null;
    }
  }
});
